#include "KMNetMsgIn.h"
#include <cstdlib>
#include "enet/enet.h"

KMNetMsgIn::KMNetMsgIn(const char *data,unsigned int length):
    mData(data), mLength(length), mPos(0)
{
}


KMNetMsgIn::~KMNetMsgIn()
{
}

bool KMNetMsgIn::readId(int &id)
{
    return read2Bytes(id);
}

bool KMNetMsgIn::readString(std::string &str)
{
    int length = 0;
    if( !read2Bytes(length) ||
        length <= 0 ||
        mPos + length > mLength )
    {
        return false;
    }

    const char *stringBeg = mData + mPos;
    const char *stringEnd = (const char *)memchr(stringBeg, '\0', length);
    str = std::string(stringBeg,
        stringEnd ? (stringEnd - stringBeg) : length);
    mPos += length;
    return true;
}

bool KMNetMsgIn::read2Bytes(int &val)
{
    if (mPos + 2 <= mLength)
    {
        uint16_t t;
        memcpy(&t, mData + mPos, 2);
        val = (unsigned short) ENET_NET_TO_HOST_16(t);
        mPos += 2;
        return true;
    }
    return false;
}
